<template>
  <div id="app">
    <!-- 需求1：需要全部组件缓存，每次进去只刷新数据，只需要把路由meta的keepAlive设为true即可 -->
    <keep-alive>
      <!-- 需要缓存的视图组件 -->
      <router-view v-if="$route.meta.keepAlive" />
    </keep-alive>
    <!-- 不需要缓存的视图组件 -->
    <router-view v-if="!$route.meta.keepAlive" />
    <!-- 需求2：动态设置组件是否缓存 -->
    <!-- <keep-alive :include="arr">
      <router-view :key="$route.path" />
    </keep-alive> -->
  </div>
</template>

<script>
export default {
  name: 'app',
  data() {
    return {
      arr: []
    };
  },
  computed: {
    fullPath() {
      return this.$route.query.fullPath;
    }
  },
  /*this.$router.push({
    path: '/page1',
    query: {
      fullPath: Date.parse(new Date())
    }
  });*/
  /**
   * router-view key的属性作用
   * 1.不设置router-view的key属性
   * 由于Vue 会复用相同组件, 即 /page/1 => /page/2 或者 /page?id=1 => /page?id=2 这类链接跳转时, 将不在执行created, mounted之类的钩子,
   * 这时候你需要在路由组件中, 添加beforeRouteUpdate钩子来执行相关方法拉去数据，钩子函数只会执行beforeRouteUpdate
   * 2.设置 router-view 的 key 属性值为 $route.path
   * 从/page/1 => /page/2, 由于这两个路由的$route.path并不一样, 所以组件被强制不复用, 钩子加载顺序为:
   * beforeRouteUpdate => created => mounted
   * 从/page?id=1 => /page?id=2, 由于这两个路由的$route.path一样, 所以和没设置 key 属性一样, 会复用组件, 钩子函数只会执行beforeRouteUpdate
   * 3.设置 router-view 的 key 属性值为 $route.fullPath
   * 从/page/1 => /page/2, 由于这两个路由的$route.fullPath并不一样, 所以组件被强制不复用, 钩子加载顺序为:
   * beforeRouteUpdate => created => mounted
   * 从/page?id=1 => /page?id=2, 由于这两个路由的$route.fullPath并不一样, 所以组件被强制不复用, 钩子加载顺序为:
   * beforeRouteUpdate => created => mounted
   */
  watch: {
    $route(newVal, oldVal) {
      console.log(
        'nVal:',
        newVal,
        'oVal:',
        oldVal,
        JSON.stringify(window.location.href)
      );

      // arr数组实时增删处于keepAlive状态的页面
      if (newVal.meta.keepAlive) {
        if (!this.arr.includes(newVal.name)) {
          this.arr.push(newVal.name);
        }
      } else {
        const { name } = newVal;
        if (this.arr.includes(name)) {
          const index = this.arr.findIndex(value => value === name);
          this.arr.splice(index, 1);
        }
      }

      if (oldVal.meta.keepAlive) {
        if (!this.arr.includes(oldVal.name)) {
          this.arr.push(oldVal.name);
        }
      } else {
        const { name } = oldVal;
        if (this.arr.includes(name)) {
          const index = this.arr.findIndex(value => value === name);
          this.arr.splice(index, 1);
        }
      }
      if (newVal) {
        switch (newVal.name) {
          case 'index':
          case 'search':
            if (!this.arr.includes(newVal.name)) {
              this.arr.push(newVal.name);
            }
            break;
          default:
            break;
        }
      }
    }
  },
  mounted() {
    console.log('app===mounted', this.$route.fullPath);
  }
};
</script>
